package es.udc.acs.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import es.udc.acs.parser.ParserMensaje;
import es.udc.acs.utils.CodigosFAP;


public class ThreadServer extends Thread{
	private DatagramSocket socket;
	private DatagramPacket packet;
	private QuestionServer server;
	
	public ThreadServer(DatagramSocket s, DatagramPacket p, QuestionServer qServer){
		socket = s;
		packet = p;
		server = qServer;
	}

	@Override
	public void run() {
		
		String request = new String(packet.getData(),0,packet.getLength());
		String response = server.procesarPregunta(request);

		try {
			// si estamos en modo de no responder
			if (!ParserMensaje.obtenerTipo(response).
					equals(CodigosFAP.NO_RESPUESTA)) {
			
				DatagramPacket packetResponse = new DatagramPacket(
						response.getBytes(), 
						response.length(), 
						packet.getAddress(), 
						packet.getPort());
				socket.send(packetResponse);
			} else {
				System.out.println("#El servidor ha rechazado la peticion.");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
